<template>
  <el-dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    width="900px"
    @close="closeDialog"
  >
    <div
      style="
        display: flex;
        align-items: center;
        justify-self: center;
        width: 100%;
      "
    >
      <el-transfer
        v-model="leftValue"
        :button-texts="['去掉', '添加']"
        :data="roleList"
        filterable
        :format="{
          noChecked: '${total}',
          hasChecked: '${checked}/${total}',
        }"
        :render-content="renderFunc"
        style="display: inline-block; margin: 0 auto; text-align: left"
        :titles="['未拥有', '已拥有']"
        @change="handleChange"
      />
    </div>
    <template #footer>
      <el-button @click="closeDialog">取 消</el-button>
      <el-button type="primary" @click="save">保 存</el-button>
    </template>
  </el-dialog>
</template>
<script setup>
  import { getUserRoleApi } from '@/api/comdesk/role'
  import { changeUserRoleApi } from '@/api/comdesk/user'
  // const $baseLoading = inject('$baseLoading')
  const $baseMessage = inject('$baseMessage')
  import { localStorageConfig } from '@/config/localstorage.config'

  const pkCorp = localStorage.getItem(localStorageConfig.__pkCorp)
  const dialogVisible = ref(false),
    dialogTitle = '修改用户权限',
    roleList = ref([]),
    leftValue = ref([])
  let userRecord = null

  const openUserChangeRolesDialog = (record) => {
    dialogVisible.value = true
    userRecord = record
    getRoles()
  }

  const getRoles = async () => {
    if (userRecord) {
      var params = { pkUser: userRecord.pkUser, pkCorp: pkCorp }
      const res = await getUserRoleApi(params)
      if (res && res.code === 2000) {
        res.data.allRoles.forEach((dItem) => {
          dItem['key'] = dItem['pkRole']
          dItem['label'] = dItem['roleName']
        })
        roleList.value = res.data.allRoles
        leftValue.value = res.data.userRoles
      }
    }
  }

  const save = async () => {
    const params = {
      pkUser: userRecord.pkUser,
      roles: leftValue.value,
      pkCorp: pkCorp,
    }
    console.log(params)
    const res = await changeUserRoleApi(params)
    if (res && res.code === 2000) {
      $baseMessage('操作成功', 'success')
      _emit('success-callback')
      closeDialog()
    } else {
      $baseMessage(res && res.msg ? res.msg : '操作失败,请重试', 'success')
    }
  }

  const renderFunc = (h, option) => {
    return h('span', null, option.label)
  }
  const handleChange = () => {
    //
  }
  const closeDialog = () => {
    dialogVisible.value = false
  }
  defineExpose({ openUserChangeRolesDialog })
  const _emit = defineEmits(['success-callback'])

  onMounted(() => {
    getRoles()
  })
</script>
